package cn.iocoder.yudao.module.scrm.service.customerassistants;

import cn.hutool.core.bean.BeanUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission;
import cn.iocoder.yudao.module.scrm.controller.admin.customerassistants.vo.CustomerAssistantsPageReqVO;
import cn.iocoder.yudao.module.scrm.controller.admin.customerassistants.vo.CustomerAssistantsSaveReqVO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.customerassistants.CustomerAssistantsDO;
import cn.iocoder.yudao.module.scrm.dal.mysql.customerassistants.CustomerAssistantsMapper;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.mzt.logapi.context.LogRecordContext;
import com.mzt.logapi.starter.annotation.LogRecord;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.scrm.enums.ErrorCodeConstants.CUSTOMER_ASSISTANTS_NOT_EXISTS;
import static cn.iocoder.yudao.module.scrm.enums.ErrorCodeConstants.CUSTOMER_ASSISTANTS_USER_ID_OR_WX_ID_REQUIRED;
import static cn.iocoder.yudao.module.scrm.enums.LogRecordConstants.*;

/**
 * 客户协作人 Service 实现类
 *
 * @author admin
 */
@Service
@Validated
public class CustomerAssistantsServiceImpl implements CustomerAssistantsService {

    @Resource
    private CustomerAssistantsMapper customerAssistantsMapper;

    @Resource
    private AdminUserApi adminUserApi;

    @Override
    @LogRecord(type = SCRM_CUSTOMER_TYPE, subType = SCRM_CUSTOMER_ASSISTANTS_TYPE, bizNo = "{{#createReqVO.customerId}}",
            success = SCRM_CUSTOMER_ASSISTANTS_CREATE_SUB_TYPE)
    public void createCustomerAssistants(CustomerAssistantsSaveReqVO createReqVO) {
        // 插入
        List<CustomerAssistantsDO> customerAssistants = convert(createReqVO);
        List<Long> userIds = customerAssistants.stream().map(CustomerAssistantsDO::getUserId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(userIds)) {
            List<AdminUserRespDTO> userList = adminUserApi.getUserListNotCheckDataPermission(userIds).getCheckedData();
            // 将用户昵称转成用逗号分割的字符串
            List<String> nicknames = userList.stream().map(AdminUserRespDTO::getNickname).collect(Collectors.toList());
            String users = String.join(",", nicknames);
            LogRecordContext.putVariable("users", users);
        }
        customerAssistantsMapper.insertBatch(customerAssistants);
    }

    @Override
    public void updateCustomerAssistants(CustomerAssistantsSaveReqVO updateReqVO) {
        // 校验存在
        validateCustomerAssistantsExists(updateReqVO.getId());
        // 更新
        CustomerAssistantsDO updateObj = BeanUtils.toBean(updateReqVO, CustomerAssistantsDO.class);
        customerAssistantsMapper.updateById(updateObj);
    }

    @Override
    public void deleteCustomerAssistants(Long id) {
        // 校验存在
        validateCustomerAssistantsExists(id);
        // 删除
        customerAssistantsMapper.deleteById(id);
    }

    private void validateCustomerAssistantsExists(Long id) {
        if (customerAssistantsMapper.selectById(id) == null) {
            throw exception(CUSTOMER_ASSISTANTS_NOT_EXISTS);
        }
    }

    @Override
    public CustomerAssistantsDO getCustomerAssistants(Long id) {
        return customerAssistantsMapper.selectById(id);
    }

    @Override
    public PageResult<CustomerAssistantsDO> getCustomerAssistantsPage(CustomerAssistantsPageReqVO pageReqVO) {
        return customerAssistantsMapper.selectPage(pageReqVO);
    }

    @Override
    @DataPermission(enable = false)
    public List<AdminUserRespDTO> getCustomerAssistantsList(Long customerId) {
        // 查询客户助理列表
        List<CustomerAssistantsDO> customerAssistantsList = customerAssistantsMapper.selectList(CustomerAssistantsDO::getCustomerId, customerId);

        // 空值检查
        if (customerAssistantsList == null || customerAssistantsList.isEmpty()) {
            // 如果列表为空，直接返回空列表
            return Collections.emptyList();
        }

        // 提取用户ID列表
        List<Long> userIds = customerAssistantsList.stream()
                .map(CustomerAssistantsDO::getUserId)
                .collect(Collectors.toList());

        // 调用API获取用户列表
        CommonResult<List<AdminUserRespDTO>> resp = adminUserApi.getUserListNotCheckDataPermission(userIds);

        // 检查API响应
        if (resp == null || !resp.isSuccess()) {
            return Collections.emptyList();
        }

        // 返回用户列表
        return resp.getData();
    }

    private List<CustomerAssistantsDO> convert(CustomerAssistantsSaveReqVO saveReqVO) {
        if (CollectionUtils.isEmpty(saveReqVO.getUserIds()) && CollectionUtils.isEmpty(saveReqVO.getWxIds())) {
            throw exception(CUSTOMER_ASSISTANTS_USER_ID_OR_WX_ID_REQUIRED);
        }
        List<CustomerAssistantsDO> doList = new ArrayList<>();
        if (CollectionUtils.isEmpty(saveReqVO.getUserIds())) {
            for (String wxId : saveReqVO.getWxIds()) {
                // 获取用户ID并使用Optional包装
                getIdOptional(wxId).ifPresent(userId -> {
                    CustomerAssistantsDO customerAssistantsDO = new CustomerAssistantsDO();
                    // 复制公共属性
                    BeanUtil.copyProperties(saveReqVO, customerAssistantsDO);
                    // 设置用户ID
                    customerAssistantsDO.setUserId(userId);
                    doList.add(customerAssistantsDO);
                });
            }
        } else {
            for (Long userId : saveReqVO.getUserIds()) {
                CustomerAssistantsDO customerAssistantsDO = new CustomerAssistantsDO();
                // 复制公共属性
                BeanUtil.copyProperties(saveReqVO, customerAssistantsDO);
                // 设置用户ID
                customerAssistantsDO.setUserId(userId);
                doList.add(customerAssistantsDO);
            }
        }
        return doList;
    }

    private Optional<Long> getIdOptional(String wxId) {
        return Optional.ofNullable(adminUserApi.getUserByWxId(wxId))
                .flatMap(response -> Optional.ofNullable(response.getData()))
                .map(AdminUserRespDTO::getId);
    }

}